package syscontrollers

import (
	"myadmin/sys/syscontrollers/syscommon"
	"myadmin/sys/sysmodels"
	"strconv"
	"strings"
)

/*
权限与开发有关 所以此处只有权限的查询 没有增删改功能
 */
type SysAuth struct {
	syscommon.BaseController
}

func (c *SysAuth) URLMapping() {
	c.Mapping("Get", c.Get)
	c.Mapping("Get2", c.Get2)
}

//@Title 查询角色
//@Description 查询角色
//@Param authname url string fase 角色标识
//@success 200 {json} 权限json数据
//@Failure 500 {json} 创建失败
//@router /auth [get]
func (this *SysAuth) Get() {
	auth := sysmodels.NewSysAuth()
	page := this.GetString("page")
	p := this.S2i(page, 1)
	limit := this.GetString("limit")
	l := this.S2i(limit, 20)
	authname := this.GetString("authname")
	auth.AuthName = authname
	roles, cnt := auth.Query(l, p)
	this.JsonReqStdS(200, int(cnt), l, p, roles)
}

//@Title 根据角色生成权限
//@Description 根据角色生成权限
//@Param roleid path string fase 角色id
//@success 200 {json} 权限json数据
//@Failure 500 {json} 创建失败
//@router /auth/role/:id [get]
func (this *SysAuth) Get2() {
	_id := this.Ctx.Input.Param(":id")
	id, err := strconv.Atoi(_id)
	if err != nil {
		this.JsonRep500("无效id")
		return
	}
	auth := sysmodels.NewSysAuth()
	role := sysmodels.NewRole()
	role.Id = id
	err = role.GetById()
	if err != nil {
		this.JsonRep500(err.Error())
		return
	}
	authlist, _ := auth.GetAuthAll()
	roleauth:= role.AuthList
	m := make([]map[string]interface{}, 0, len(*authlist))
	for _,v:=range *authlist{
		var checked = false
		for _,aut := range roleauth{
			if aut == v.AuthName{
				checked = true
				break
			}
		}
		m = append(m,map[string]interface{}{
			"open":true,
			"checked":checked,
			"pid":v.Pid,
			"id":v.Id,
			"name":strings.Join([]string{v.Name,v.Api}," "),
		})
	}
	this.JsonRep200x("ok",m)

}
